﻿using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace suirui.ZhuMu.WebCore
{
    public class CustomResourceFilterAttribute : Attribute, IResourceFilter
    {
        //建立缓存字典
        private static Dictionary<string, object> cacheList = new Dictionary<string, object>();
        private readonly ILogger<CustomResourceFilterAttribute> logger;

        public CustomResourceFilterAttribute(ILoggerFactory loggerFactory)
        {
            logger = loggerFactory.CreateLogger<CustomResourceFilterAttribute>();
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            logger.LogInformation("ResourceFilter Executed!");

            //将取到的值存储到缓存中
            string key = context.HttpContext.Request.Path;
            cacheList[key] = context.Result;
        }

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            //使用当前url地址做为key
            string key = context.HttpContext.Request.Path;
            //通过key判断是否存在缓存
            if (cacheList.ContainsKey(key))
            {
                logger.LogInformation("From ResourceFilter Cache Executing!");
                //对断路器赋值,直接返回给客户端
                context.Result = cacheList[key] as IActionResult ;
            }
        }
    }
}
